<template>
  <el-dialog
    title="代码预览"
    :close-on-click-modal="false"
    v-model="isShow"
    width="1100px"
    @close="close"
  >
     <el-tabs v-model="preview.activeName">
      <el-tab-pane
        v-for="(value, key) in preview.data"
        :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
        :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
        :key="key"
      >
      <pre><code class="hljs" v-html="highlightedCode(value, key)" /></pre>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script lang="ts">
import { useStore } from 'vuex'
import { toRefs, ref, computed, watch, defineComponent } from 'vue'
import dialog from '@/mixins/dialog'
import hljs from 'highlight.js/lib/core'
import 'highlight.js/styles/github-gist.css'
import { StateType as GenCodeStateType } from '@/store/modules/system/genCode'
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('java', require('highlight.js/lib/languages/java'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('html', require('highlight.js/lib/languages/xml'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('vue', require('highlight.js/lib/languages/xml'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('typescript', require('highlight.js/lib/languages/typescript'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'))
export default defineComponent({
  name: 'PreviewCode',
  emits: ['onRefresh', 'close'], // this line
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const store = useStore<{genCode: GenCodeStateType}>()
    const { dialogM } = dialog(props, context)
    const data = computed(() => {
      return store.state.genCode.preview
    })
    const preview = ref({
      activeName: 'domain.java',
      data: []
    })
    watch(() => props.value, (val) => {
      if (val) {
        preview.value.data = data.value as any
      }
    })
    const highlightedCode = (code: string, key: string) => {
      const vmName = key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))
      const language = vmName.substring(vmName.indexOf('.') + 1, vmName.length)
      const result = hljs.highlight(language, code || '', true)
      return result.value || '&nbsp;'
    }
    return {
      highlightedCode,
      preview,
      ...toRefs(dialogM)
    }
  }
})
</script>
